import uuid from "@/utils/uuid";
import {getUserInfoAPI, loginAPI, logoutAPI} from "@/api/userApi";
import {getToken, removeToken, setToken} from "@/utils/localStorage";

const actions = {
    /* 登录的actions */
    async userLogin(context, data) {
        const result = await loginAPI(data)
        if (result.code !== 200) return Promise.reject(result.message)
        context.commit("setToken", result.data.token)
        return Promise.resolve(result.message)
    },

    /* 退出登录的actions */
    async userLogout(context) {
        const result = await logoutAPI()
        if (result.code !== 200) return Promise.reject("退出失败")
        context.commit("clearToken")
        context.commit("clearUserInfo")
        return Promise.resolve("退出成功")
    },

    /* 获取用户信息的actions */
    async fetchUserInfo(context) {
        const result = await getUserInfoAPI()
        if (result.code !== 200) return Promise.reject(result.message)
        context.commit("setUserInfo", result.data)
        return Promise.resolve(result.message)
    }

}
const mutations = {
    /* 设置token的mutations */
    setToken(state, token) {
        state.token = token
        setToken(token)
    },
    /* 清空token的mutations */
    clearToken(state) {
        state.token = ""
        removeToken()
    },
    /* 设置用户信息的mutations */
    setUserInfo(state, userInfo) {
        state.userInfo = userInfo
    },
    /* 清空用户信息的mutations */
    clearUserInfo(state) {
        state.userInfo = {}
    }
}
const state = () => {
    return {
        // 游客的临时身份
        uuid: uuid(),
        // 用户身份令牌
        token: getToken() || "",
        //  用户信息
        userInfo: {}
    }
}
const getters = {}
export default {
    actions,
    mutations,
    state,
    getters,
    namespaced: true
}
